//
//  HoFiler.swift
//  HoFileHelper.swift
//  HoUIit
//
//  Created by Hoa on 2020/5/21.
//

import Foundation
import UIKit

struct HoFileHelper {
    
    static func url(for fileName: String) -> URL? {
        var cache: [String: URL] = [:] // Save all local files in this cache
        let baseURL = urlForRestServicesTestsDir()
        
        guard let enumerator = FileManager.default.enumerator(
            at: baseURL,
            includingPropertiesForKeys: [.nameKey],
            options: [.skipsHiddenFiles, .skipsPackageDescendants],
            errorHandler: nil) else {
                fatalError("Could not enumerate \(baseURL)")
        }
        
        for case let url as URL in enumerator where url.isFileURL {
            cache[url.lastPathComponent] = url
        }
        return cache[fileName]
    }
    
    static func urlForRestServicesTestsDir() -> URL {
        let currentFileURL = URL(fileURLWithPath: "\(#file)", isDirectory: false)
        return currentFileURL
            .deletingLastPathComponent()
            .deletingLastPathComponent()
    }
    
    static func image(for imageName: String) -> UIImage? {
        if let url = url(for: imageName) {
            if let data = try? Data(contentsOf: url) {
                let image = UIImage(data: data)
                return image
            }
        }
        return nil
    }
    
    static func nib(for nibName: String) -> UINib? {
        if let url = url(for: nibName) {
            if let data = try? Data(contentsOf: url) {
                let nib = UINib.init(data: data, bundle: Bundle.init(url: url))
                return nib
            }
        }
        return nil
    }
}
